<?php

namespace common\sms;

use Exception;
use App\Services\HallDomainService;
use App\Models\SmsConfig;

class SMSManager
{

    // 短信API
    const SENDER_MAPS = [
        'yuntongxun' => 'common\sms\yuntongxun\Sender',
        'dingdongyun' => 'common\sms\dingdongyun\Sender',
    ];

    protected static $senders = [];

    /**
     * @param string $code
     * @param string $config
     * @return SenderInterface
     */
    public static function setSender($code, $config)
    {
        $hall_id = HallDomainService::getHallID();
        $class = self::SENDER_MAPS[$code];
        $sender = new $class();
        // 初始化失败
        if (!$sender->init(json_decode($config, true))) {
            throw Exception("Hall $hall_id SMS init fail! " . $config);
        }
        self::$senders[$hall_id] = $sender;
        return $sender;
    }

    /**
     * @return SenderInterface
     */
    public static function getSender()
    {
        $hall_id = HallDomainService::getHallID();
        $config = SmsConfig::where(['status' => 1])->first();
        if (!$config) {
            throw Exception("Hall $hall_id sms_config not found!");
        }
        $code = $config['code'];
        if (!isset(self::SENDER_MAPS[$code])) {
            throw Exception("Hall $hall_id sms_config Error! Code $code not exist!");
        }
        if (isset(self::$senders[$hall_id])) {
            return self::$senders[$hall_id];
        }
        return self::setSender($code, $config['config']);
    }

    /**
     * @param string $mobile
     * @param array  $template
     * @return bool
     */
    public static function send($mobile, $template)
    {
        $sender = static::getSender();
        if (!$sender->checkTemplate($template)) {
            $sender->setErrorMsg('CheckTemplate Error:' . json_encode($template));
            return false;
        }
        return $sender->send($mobile, $template);
    }

    /**
     * @param string     $mobile
     * @param string|int $code
     * @param int        $m
     * @return bool
     */
    public static function sendValidMsg($mobile, $code, $m = 10)
    {
        return static::getSender()->sendValidMsg($mobile, $code, $m);
    }

    /**
     * @return string
     */
    public static function getErrorMsg()
    {
        return static::getSender()->getErrorMsg();
    }
}
